package com.shengwei.truck.driver.view.ui.map;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.lifecycle.Observer;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.shengwei.truck.driver.R;
import com.shengwei.truck.driver.third_sdk.baidu.BitmapUtil;
import com.shengwei.truck.driver.bean.JsonTrackData;
import com.shengwei.truck.driver.bean.LocationPack;
import com.shengwei.truck.driver.bean.Result;
import com.shengwei.truck.driver.databinding.ActivityTrackBinding;
import com.shengwei.truck.driver.utils.CommonUtil;
import com.shengwei.truck.driver.utils.DateTimeUtils;
import com.shengwei.truck.driver.utils.MyLogCat;
import com.shengwei.truck.driver.view.ui.BaseActivity;
import com.shengwei.truck.driver.vm.TrackViewModel;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import static com.shengwei.truck.driver.third_sdk.baidu.BitmapUtil.bmEnd;
import static com.shengwei.truck.driver.third_sdk.baidu.BitmapUtil.bmStart;

/**
 * 轨迹展示
 */
public class TrackShowActivity extends BaseActivity<TrackViewModel, ActivityTrackBinding> implements View.OnClickListener {
    private BaiduMap mBaiduMap;
    private Polyline mPolyline;
    private Marker mMoveMarker;
    private Handler mHandler;
    // 通过设置间隔时间和距离可以控制速度和图标移动的距离
    private static final int TIME_INTERVAL = 80;
    private static final double DISTANCE = 0.00002;
    private BitmapDescriptor mGreenTexture = BitmapDescriptorFactory.fromAsset("Icon_road_green_arrow.png");
    private BitmapDescriptor mBitmapCar = BitmapDescriptorFactory.fromResource(R.drawable.car);
    //绘制轨迹
    public LatLngBounds mLatLngBounds = null; //保证轨迹点在同一屏幕视野内。
    private MapStatus mMapStatus = null;
    private boolean mIsStopMoveTrack = false;
    //当前正在进行的任务ID
    private String mCurTaskId;
    private final String TAG = "TrackShowActivity";

    //开始时分秒默认是  从早上0：00开始
    private long mStartTime = DateTimeUtils.getTimesmorningMs();
    //结束时间默认是现在时刻
    private long mEndTime = DateTimeUtils.getCurrentTimeMs();

    private int mYearStart;
    private int mMonthStart;
    private int mDayStart;
    private int mHourStart;
    private int mMinuteStart;

    private int mYearEnd;
    private int mMonthEnd;
    private int mDayEnd;
    private int mHourEnd;
    private int mMinuteEnd;

    static final int DATE_DIALOG_ID_START = 0;
    static final int TIME_DIALOG_ID_START = 1;
    static final int DATE_DIALOG_ID_END = 2;
    static final int TIME_DIALOG_ID_END = 3;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDataBinding.bmapView.onCreate(this, savedInstanceState);
        initView();
        initBaiduMap();
        getLastIntent();
        initLiveDataObersve();
        //用于更新小车移动
        mHandler = new Handler(Looper.getMainLooper());
    }

    private void initView() {
        String strCurTime = DateTimeUtils.getDateTimeYMD(mStartTime);
        mDataBinding.tvDate.setText(strCurTime);
        final Calendar c = Calendar.getInstance();
        mYearStart = mYearEnd = c.get(Calendar.YEAR);
        mMonthStart = mMonthEnd = c.get(Calendar.MONTH);
        mDayStart = mDayEnd = c.get(Calendar.DAY_OF_MONTH);
        mHourStart = mHourEnd = c.get(Calendar.HOUR_OF_DAY);
        mMinuteStart = mMinuteEnd =c.get(Calendar.MINUTE);
        initStartTime();
        initEndTime();
        mDataBinding.tvDate.setOnClickListener(this);
        mDataBinding.tvPickTimeStart.setOnClickListener(this);
        mDataBinding.tvPickTimeEnd.setOnClickListener(this);
        mDataBinding.btSelect.setOnClickListener(this);
    }
    public void initStartTime()
    {
        long todayZero = DateTimeUtils.getTimesmorningMs();
        String startDateTime = DateTimeUtils.getDateTime(todayZero);
        String split[] = startDateTime.split("/");
        String []splitYmd = split[0].split("-");  //年月日
        mYearStart = Integer.valueOf(splitYmd[0]);
        mMonthStart = Integer.valueOf(splitYmd[1])-1;  //因为updateDisplay里边现在是+1,
        mDayStart = Integer.valueOf(splitYmd[2]);

        String []splitMhs = split[1].split(":"); //时分秒
        mHourStart = Integer.valueOf(splitMhs[0]);
        mMinuteStart = Integer.valueOf(splitMhs[1]);

        StringBuilder builderDateStart =  new StringBuilder()
                // Month is 0 based so add 1
                .append(mYearStart).append("-")
                .append(pad(mMonthStart + 1)).append("-")
                .append(pad(mDayStart));


        StringBuilder builderTimeStart =  new StringBuilder()
                // Month is 0 based so add 1
                .append(pad(mHourStart)).append(":")
                .append(pad(mMinuteStart));

        mDataBinding.tvDate.setText(builderDateStart.toString());
        mDataBinding.tvPickTimeStart.setText(builderTimeStart.toString());
        Log.i(TAG,"start-dtime = "+builderDateStart.toString()+" ,"+builderTimeStart.toString());
    }

    private static String pad(int c) {
        if (c >= 10)
            return String.valueOf(c);
        else
            return "0" + String.valueOf(c);
    }

    public void initEndTime() {
        long todayNow = DateTimeUtils.getCurrentTimeMs();
        String startDateTime = DateTimeUtils.getDateTime(todayNow);
        String split[] = startDateTime.split("/");
        String []splitYmd = split[0].split("-");  //年月日
        mYearEnd = Integer.valueOf(splitYmd[0]);
        mMonthEnd = Integer.valueOf(splitYmd[1])-1;
        mDayEnd = Integer.valueOf(splitYmd[2]);

        String []splitMhs = split[1].split(":"); //时分秒
        mHourEnd = Integer.valueOf(splitMhs[0]);
        mMinuteEnd = Integer.valueOf(splitMhs[1]);
        updateDisplay(1);
    }

    /**
     *
     * @param type: 0更新开始时间，1更新结束时间
     */
    private void updateDisplay(int type) {
        if(type == 0)
        {

            StringBuilder builderDateStart =  new StringBuilder()
                    // Month is 0 based so add 1
                    .append(mYearStart).append("-")
                    .append(pad(mMonthStart + 1)).append("-")
                    .append(pad(mDayStart));


            StringBuilder builderTimeStart =  new StringBuilder()
                    // Month is 0 based so add 1
                    .append(pad(mHourStart)).append(":")
                    .append(pad(mMinuteStart));

            mDataBinding.tvDate.setText(builderDateStart.toString());
            mDataBinding.tvPickTimeStart.setText(builderTimeStart.toString());
            Log.i(TAG,"start-dtime = "+builderDateStart.toString()+" ,"+builderTimeStart.toString());

        }
        else {
            StringBuilder builderDateEnd =  new StringBuilder()
                    // Month is 0 based so add 1
                    .append(mYearEnd).append("-")
                    .append(pad(mMonthEnd + 1)).append("-")
                    .append(pad(mDayEnd));


            StringBuilder builderTimeEnd =  new StringBuilder()
                    // Month is 0 based so add 1
                    .append(pad(mHourEnd)).append(":")
                    .append(pad(mMinuteEnd));

            //gxw- btPickDateEnd.setText(builderDateEnd.toString());
            mDataBinding.tvPickTimeEnd.setText(builderTimeEnd.toString());
            Log.i(TAG,"END-dtime = "+builderDateEnd.toString()+" ,"+builderTimeEnd.toString());
        }


    }
    /**
     * 获取上一页的数据
     */
    public void getLastIntent() {
        Intent i = this.getIntent();
        Bundle bundle = i.getExtras();
        if(bundle != null) {
            mCurTaskId = bundle.getString("taskId");
        }
    }

    @Override
    protected void onStart() {
        MyLogCat.i(TAG,"onStart");
        super.onStart();
    }

    @Override
    protected void onResume() {
        MyLogCat.i(TAG,"onResume");
        super.onResume();
        mDataBinding.bmapView.onResume();
        refreshTrack();
    }

    public void refreshTrack(){
        clearTrack();
        mViewModel.getTrack(mCurTaskId,mStartTime,mEndTime);
    }

    @Override
    protected void onPause() {
        MyLogCat.i(TAG,"onPause");
        super.onPause();
        mDataBinding.bmapView.onPause();
    }
    @Override
    protected void onStop() {
        MyLogCat.i(TAG,"onStop");
        clearTrack();
        super.onStop();
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mDataBinding.bmapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        MyLogCat.i(TAG,"onDestroy");
        super.onDestroy();
        mIsStopMoveTrack = true;  //停止小车轨迹MOVE播放
        clearTrack();//清除轨迹

        //释放图片资源，地图状态，边界对象等
        mMapStatus = null;
        mBitmapCar.recycle(); //小车图片
        mGreenTexture.recycle();//纹理图片
        if(bmStart != null) {  //起点图标
            bmStart.recycle();
        }
        if(bmEnd != null) { //结束图标
            bmEnd.recycle();
        }
        mDataBinding.bmapView.onDestroy();
    }

    /**
     * 初始化地图
     */
    public void initBaiduMap() {
        mDataBinding.bmapView.showZoomControls(false);
        mBaiduMap = mDataBinding.bmapView.getMap();
        mBaiduMap.getUiSettings().setRotateGesturesEnabled(false);
        animateMapStatus(null,19.0f);
    }
    /**
     * 创建liveData观察者，用于监听数据变化，从而更新UI
     */
    private void initLiveDataObersve() {
        //监听获取轨迹的接口
        mViewModel.getTrackLiveData().observe(this, new Observer<Result<JsonTrackData>>() {
            @Override
            public void onChanged(Result<JsonTrackData> trackDataResult) {
                trackDataResult.handler(new OnCallback<JsonTrackData>() {
                    @Override
                    public void onSuccess(JsonTrackData data) {
                        List<LocationPack> locList =  data.getLocations();
                        //更新轨迹
                        updateTrackPoint(locList);
                    }
                });
            }
        });
    }

    /**
     * 更新地图上的轨迹点
     * @param locList:从服务器获取的轨迹点
     */
    public void updateTrackPoint(List<LocationPack> locList) {
        if(locList != null) {
            //得到位置点集合latLngs
            List<LatLng> latLngs= new ArrayList<>(); //目前位置都是百度坐标系
            int size = locList.size();
            if(size > 0) {
                for(int i = 0; i < size; i++) {
                    double lat = Double.parseDouble(locList.get(i).getLat());
                    double lng = Double.parseDouble(locList.get(i).getLng());
                    LatLng latLng = new LatLng(lat,lng);
                    latLngs.add(latLng);
                }
                //在地图上制轨迹点集合(latLngs)成线段，并实现平滑移动小车
                drawPolyLine(latLngs);
            }
        }
    }

    /**
     * 绘制轨迹点在地图上：(1)绘制各点成线(2)小车平滑的移动在线段上
     * @param polylines
     */
    private void drawPolyLine(List<LatLng> polylines) {
        mBaiduMap.clear();
        int size = polylines.size();
        if(size == 0) {
            if (null != mPolyline) {
                mPolyline.remove();
                mPolyline = null;
            }
            return;
        }
        BitmapUtil.init();
        //只有1个点
        if (size == 1) {
            OverlayOptions startOptions = new MarkerOptions().position(polylines.get(0)).icon(bmStart)
                    .zIndex(9).draggable(true);
            mBaiduMap.addOverlay(startOptions);
            animateMapStatus(polylines.get(0), 19.0f);
            return;
        }
        else{  //多个点

            // 添加起点图标
            LatLng startPoint = polylines.get(0);
            OverlayOptions startOptions = new MarkerOptions().position(startPoint).icon(bmStart).zIndex(20).draggable(true);
            mBaiduMap.addOverlay(startOptions);
            // 添加终点图标
            LatLng endPoint = polylines.get(size -1);
            OverlayOptions endOptions = new MarkerOptions().position(endPoint).icon(bmEnd).zIndex(18).draggable(true);
            mBaiduMap.addOverlay(endOptions);

            //同一视野内显示轨迹点集合
            showTrackInView(polylines);

            //绘制轨迹线段，颜色值格式0xAARRGGBB，绘制纹理：PolyLine.customTexture(mGreenTexture).dottedLine(true)
            PolylineOptions polylineOptions = new PolylineOptions().points(polylines).width(10).color(Color.RED).customTexture(mGreenTexture);
            mPolyline = (Polyline) mBaiduMap.addOverlay(polylineOptions);

            //小车平滑移动在轨迹线上
           // moveLooper(polylines);gxw-要恢复
        }
    }

    /**
     * 显示轨迹在同一屏幕视野
     * @param baiduPoints
     */
    public void showTrackInView(List<LatLng> baiduPoints) {
        //获得同一屏幕视野边界
        mLatLngBounds = getLatLngBounds(baiduPoints);
        //刷新地图显示 同一视野内的轨迹点
        animateMapStatus(mLatLngBounds);
    }

    /**
     * 刷新地图 同一视野内的轨迹点
     * @param latLngBounds
     */
    public void animateMapStatus(LatLngBounds latLngBounds) {
        MapStatusUpdate msUpdate = MapStatusUpdateFactory.newLatLngBounds(latLngBounds);
        mBaiduMap.animateMapStatus(msUpdate);
    }

    /**
     * 得到当前屏幕地图视野边界
     * @param baiduPoints
     * @return
     */
    public LatLngBounds getLatLngBounds(List<LatLng> baiduPoints) {
        LatLngBounds latLngBounds;
        if (null == baiduPoints || baiduPoints.isEmpty()) {
            return null;
        }
        LatLngBounds.Builder builder = new LatLngBounds.Builder();
        for (LatLng point : baiduPoints) {
            builder.include(point);
        }
        latLngBounds = builder.build();
        return latLngBounds;
    }
    @Override
    public int getContentViewId() {
        return R.layout.activity_track;
    }

    /**
     * 移动地图中心到当前位置点
     * @param point：地图中心
     * @param zoom：地图缩放级别
     */
    public void animateMapStatus(LatLng point, float zoom) {
        MapStatus.Builder builder = new MapStatus.Builder();
        mMapStatus = builder.target(point).zoom(zoom).build();
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(mMapStatus));
    }

    /**
     * 根据点获取图标转的角度
     */
    private double getAngle(int startIndex) {
        if ((startIndex + 1) >= mPolyline.getPoints().size()) {
            throw new RuntimeException("index out of bonds");
        }
        LatLng startPoint = mPolyline.getPoints().get(startIndex);
        LatLng endPoint = mPolyline.getPoints().get(startIndex + 1);
        return getAngle(startPoint, endPoint);
    }

    /**
     * 根据两点算取图标转的角度
     */
    private double getAngle(LatLng fromPoint, LatLng toPoint) {
        double slope = getSlope(fromPoint, toPoint);
        if (slope == Double.MAX_VALUE) {
            if (toPoint.latitude > fromPoint.latitude) {
                return 0;
            } else {
                return 180;
            }
        } else if (slope == 0.0) {
            if (toPoint.longitude > fromPoint.longitude) {
                return -90;
            } else {
                return 90;
            }
        }
        float deltAngle = 0;
        if ((toPoint.latitude - fromPoint.latitude) * slope < 0) {
            deltAngle = 180;
        }
        double radio = Math.atan(slope);
        double angle = 180 * (radio / Math.PI) + deltAngle - 90;
        return angle;
    }

    /**
     * 根据点和斜率算取截距
     */
    private double getInterception(double slope, LatLng point) {
        double interception = point.latitude - slope * point.longitude;
        return interception;
    }

    /**
     * 算斜率
     */
    private double getSlope(LatLng fromPoint, LatLng toPoint) {
        if (toPoint.longitude == fromPoint.longitude) {
            return Double.MAX_VALUE;
        }
        double slope = ((toPoint.latitude - fromPoint.latitude) / (toPoint.longitude - fromPoint.longitude));
        return slope;
    }

    /**
     * 计算x方向每次移动的距离
     */
    private double getXMoveDistance(double slope) {
        if (slope == Double.MAX_VALUE || slope == 0.0) {
            return DISTANCE;
        }
        return Math.abs((DISTANCE * 1 / slope) / Math.sqrt(1 + 1 / (slope * slope)));
    }

    /**
     * 计算y方向每次移动的距离
     */
    private double getYMoveDistance(double slope) {
        if (slope == Double.MAX_VALUE || slope == 0.0) {
            return DISTANCE;
        }
        return Math.abs((DISTANCE * slope) / Math.sqrt(1 + slope * slope));
    }

    /**
     * 循环进行移动逻辑
     */
    public void moveLooper(List<LatLng> latLngs) {
        mIsStopMoveTrack = false;
        OverlayOptions markerOptions = new MarkerOptions().flat(true).anchor(0.5f, 0.5f).icon(mBitmapCar).
                position(latLngs.get(0)).rotate((float) getAngle(0));
        mMoveMarker = (Marker) mBaiduMap.addOverlay(markerOptions);
        new Thread() {
            public void run() {
                    for (int i = 0; i < latLngs.size() - 1; i++) {
                        if(mIsStopMoveTrack) {
                            Log.i(TAG,"stop in for start");
                            return;
                        }

                        final LatLng startPoint = latLngs.get(i);
                        final LatLng endPoint = latLngs.get(i+1);
                        if(mMoveMarker != null){
                            mMoveMarker.setPosition(startPoint);
                        }
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                // refresh marker's rotate
                                if ( mDataBinding.bmapView == null) {
                                    return;
                                }
                                if(mMoveMarker != null) {
                                    mMoveMarker.setRotate((float) getAngle(startPoint, endPoint));
                                }
                            }
                        });
                        double slope = getSlope(startPoint, endPoint);
                        // 是不是正向的标示
                        boolean isYReverse = (startPoint.latitude > endPoint.latitude);
                        boolean isXReverse = (startPoint.longitude > endPoint.longitude);
                        double intercept = getInterception(slope, startPoint);
                        double xMoveDistance = isXReverse ? getXMoveDistance(slope) : -1 * getXMoveDistance(slope);
                        double yMoveDistance = isYReverse ? getYMoveDistance(slope) : -1 * getYMoveDistance(slope);

                        for (double j = startPoint.latitude, k = startPoint.longitude;
                             !((j > endPoint.latitude) ^ isYReverse) && !((k > endPoint.longitude) ^ isXReverse); ) {

                            if(mIsStopMoveTrack) {
                                Log.i(TAG,"stop at before  sleep");
                                return;
                            }

                            LatLng latLng = null;

                            if (slope == Double.MAX_VALUE) {
                                latLng = new LatLng(j, k);
                                j = j - yMoveDistance;
                            } else if (slope == 0.0) {
                                latLng = new LatLng(j, k - xMoveDistance);
                                k = k - xMoveDistance;
                            } else {
                                latLng = new LatLng(j, (j - intercept) / slope);
                                j = j - yMoveDistance;
                            }

                            final LatLng finalLatLng = latLng;
                            if (finalLatLng.latitude == 0 && finalLatLng.longitude == 0) {
                                continue;
                            }
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    if ( mDataBinding.bmapView == null) {
                                        return;
                                    }
                                    if(mMoveMarker != null){
                                        mMoveMarker.setPosition(finalLatLng);
                                        // 设置 Marker 覆盖物的位置坐标,并同步更新与Marker关联的InfoWindow的位置坐标.
                                        mMoveMarker.setPositionWithInfoWindow(finalLatLng);
                                    }
                                }
                            });
                            try {
                                if(mIsStopMoveTrack) {
                                    Log.i(TAG,"stop at before  sleep");
                                    return;
                                }
                                Thread.sleep(TIME_INTERVAL);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    return;
            }
        }.start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.tv_date:
                showDialog(DATE_DIALOG_ID_START);
                break;
            case R.id.tvPickTimeStart:
                showDialog(TIME_DIALOG_ID_START);
                break;
            case R.id.tvPickTimeEnd:
                showDialog(TIME_DIALOG_ID_END);
                break;
            case R.id.btSelect:
                String startDate = mDataBinding.tvDate.getText().toString();
                String startTime =  mDataBinding.tvPickTimeStart.getText().toString();
                String endDate =  startDate;  //目前开始日期和结束日期是一样的，只查询当天的
                String endTime =  mDataBinding.tvPickTimeEnd.getText().toString();
                boolean isEndTimeOk =  DateTimeUtils.checkEndTimeOK(startDate,startTime,endDate,endTime);

                if(isEndTimeOk) {
                    mIsStopMoveTrack = true;
                    refreshQueryTime();
                    refreshTrack();
                }
                else {
                    Toast.makeText(TrackShowActivity.this,"结束时间不能小于开始时间",Toast.LENGTH_SHORT).show();
                }
                break;
        }

    }

    /**
     * 清除轨迹
     */
    public void clearTrack() {
        mIsStopMoveTrack = true;
        mBaiduMap.clear();
        //销毁小车marker标记
        if (null != mMoveMarker) {
            mMoveMarker.remove();
            mMoveMarker = null;
        }
        //销毁轨迹线
        if (null != mPolyline) {
            mPolyline.remove();
            mPolyline = null;
        }
        mLatLngBounds = null;
    }
    public void refreshQueryTime() {
        String startDate = mDataBinding.tvDate.getText().toString();
        String startTime =  mDataBinding.tvPickTimeStart.getText().toString();
        String endDate =  startDate;  //目前开始日期和结束日期是一样的，只查询当天的
        String endTime = mDataBinding. tvPickTimeEnd.getText().toString();
        String start = startDate+" "+startTime+":00";
        String end = startDate+" "+endTime+":00";
        this.mStartTime = DateTimeUtils.toTimeStamp(start,CommonUtil.MILLIS);
        this.mEndTime = DateTimeUtils.toTimeStamp(end,CommonUtil.MILLIS);
    }
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {

            case DATE_DIALOG_ID_START:
                return new DatePickerDialog(this,
                        mDateSetListenerStart,
                        mYearStart, mMonthStart, mDayStart);
            case TIME_DIALOG_ID_START:
                return new TimePickerDialog(this,
                        mTimeSetListenerStart, mHourStart, mMinuteStart, false);

            case DATE_DIALOG_ID_END:
                return new DatePickerDialog(this,
                        mDateSetListenerEnd,
                        mYearEnd, mMonthEnd, mDayEnd);
            case TIME_DIALOG_ID_END:
                return new TimePickerDialog(this,
                        mTimeSetListenerEnd, mHourEnd, mMinuteEnd, false);

        }
        return null;
    }

    private DatePickerDialog.OnDateSetListener mDateSetListenerStart =
            new DatePickerDialog.OnDateSetListener() {

                @Override
                public void onDateSet(android.widget.DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                    mYearStart = year;
                    mMonthStart = monthOfYear;
                    mDayStart = dayOfMonth;
                    updateDisplay(0);
                }
            };

    private TimePickerDialog.OnTimeSetListener mTimeSetListenerStart =
            new TimePickerDialog.OnTimeSetListener() {

                @Override
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

                    String endTime =  mDataBinding.tvPickTimeEnd.getText().toString(); //开始时间
                    String startDate = mDataBinding.tvDate.getText().toString();
                    String endDate = mDataBinding.tvDate.getText().toString();
                    String willStartTime = hourOfDay+":"+minute;

                    if(checkEndTimeSelect(startDate,willStartTime,endDate,endTime))
                    {
                        mHourStart = hourOfDay;
                        mMinuteStart = minute;
                        updateDisplay(0);
                    }
                    else
                    {
                        Toast.makeText(TrackShowActivity.this,"结束时间不能小于开始时间",Toast.LENGTH_SHORT).show();
                    }
                }
            };
    private DatePickerDialog.OnDateSetListener mDateSetListenerEnd =
            new DatePickerDialog.OnDateSetListener() {

                @Override
                public void onDateSet(android.widget.DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                    mYearEnd = year;
                    mMonthEnd = monthOfYear;
                    mDayEnd = dayOfMonth;
                    updateDisplay(1);
                }
            };

    private TimePickerDialog.OnTimeSetListener mTimeSetListenerEnd =
            new TimePickerDialog.OnTimeSetListener() {

                @Override
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

                    String startTime =  mDataBinding.tvPickTimeStart.getText().toString(); //开始时间
                    String startDate = mDataBinding.tvDate.getText().toString();
                    String endDate = mDataBinding.tvDate.getText().toString();
                    String willEndTime = hourOfDay+":"+minute;
                    if(checkEndTimeSelect(startDate,startTime,endDate,willEndTime)) {
                        mHourEnd = hourOfDay;
                        mMinuteEnd = minute;
                        updateDisplay(1);
                    }
                    else {
                        Toast.makeText(TrackShowActivity.this,"结束时间不能小于开始时间",Toast.LENGTH_SHORT).show();
                    }
                }
            };

    public boolean  checkEndTimeSelect(String startDate,String startTime,String endDate,String endTime) {
        boolean isEndTimeOk =  DateTimeUtils.checkEndTimeOK(startDate,startTime,endDate,endTime);
        if(isEndTimeOk) {
            return true;
        }
        return false;
    }
}

